package com.leyou.cart.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.pojo.AppInfo;
import com.leyou.cart.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 校验是否有合法token拦截器
 */
@Component
public class AppTokenInterceptor implements HandlerInterceptor {
  @Autowired
    private JwtProperties jwtProperties;

  @Override
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response,Object handler) {
      //1.从请求头中取出token
      String token = request.getHeader(LyConstants.APP_TOKEN_HEADER);
      //2.判断token是否存在
       if (StringUtils.isEmpty(token)){
           return false;
       }
      Payload<AppInfo> payload = null;
      //3.校验token是否合法
      try {
          payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), AppInfo.class);
      } catch (Exception e) {
          e.printStackTrace();
      }
      //4.取出token的载荷的目标服务列表
      AppInfo appinfo = payload.getInfo();
      List<String> targetList = appinfo.getTargetList();
      //5.判断当前服务是否在目标服务列表中，在，则方法，不在，拒绝访问
      if (!targetList.contains(jwtProperties.getApp().getServiceName())){
          return false;
      }
      return true;
  }
}
